#include <iostream>
#include <string>
#include <memory>
#include <limits> // 必须包含

template <typename T>
class CustomAllocatorNoThrow {
public:
    using value_type = T;

    T* allocate(std::size_t n, bool& success) noexcept {
        success = true; // 默认成功
        if (n > std::numeric_limits<std::size_t>::max() / sizeof(T)) {
            success = false;
            return nullptr; // 内存不足
        }
        void* ptr = std::malloc(n * sizeof(T));
        if (!ptr) {
            success = false;
            return nullptr; // 分配失败
        }
        return static_cast<T*>(ptr);
    }

    void deallocate(T* ptr, std::size_t n) noexcept {
        std::cout << "Deallocating " << n << " element(s) of size " << sizeof(T) << "\n";
        std::free(ptr);
    }
};

// 自定义字符串类型
template <typename Allocator = CustomAllocatorNoThrow<char>>
class SafeString {
public:
    explicit SafeString(Allocator alloc = Allocator()) : allocator_(alloc), data_(nullptr), size_(0) {}

    bool allocate(std::size_t n) {
        bool success;
        data_ = allocator_.allocate(n, success);
        if (success) {
            size_ = n;
        }
        return success;
    }

    ~SafeString() {
        if (data_) {
            allocator_.deallocate(data_, size_);
        }
    }

private:
    Allocator allocator_;
    char* data_;
    std::size_t size_;
};

int main() {
    SafeString<> safeStr;

    if (!safeStr.allocate(100)) {
        std::cerr << "Memory allocation failed\n";
        return 1;
    }

    std::cout << "Memory allocated successfully\n";
    return 0;
}
